package shuaige.jdk.多线程.锁.可重入锁;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Condition_条件使用示例2_实现阻塞队列<E> {
    /**
     * 阻塞队列最大容量
     */
    int size;
    ReentrantLock lock = new ReentrantLock();
    /**
     * 队列底层实现
     */
    LinkedList<E> list = new LinkedList<>();
    /**
     * 队列满时的等待条件
     */
    Condition notFull = lock.newCondition();
    /**
     * 队列空时的等待条件
     */
    Condition notEmpty = lock.newCondition();

    public Condition_条件使用示例2_实现阻塞队列(int size) {
        this.size = size;
    }

    public static void main(String[] args) throws InterruptedException {

        Condition_条件使用示例2_实现阻塞队列<Integer> queue = new Condition_条件使用示例2_实现阻塞队列<>(2);
        for (int i = 0; i < 10; i++) {
            int data = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 入队
                        queue.enqueue(data);
                    } catch (InterruptedException e) {

                    }
                }
            }).start();

        }
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 出队
                        Integer data = queue.dequeue();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }

    /**
     * 入队
     */
    public void enqueue(E e) throws InterruptedException {
        lock.lock();
        try {
            // 队列已满,在notFull条件上等待
            while (list.size() == size) {
                notFull.await();
            }
            // 入队:加入链表末尾
            list.add(e);
            System.out.println("入队：" + e);
            // 通知在notEmpty条件上等待的线程
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 出队
     */
    public E dequeue() throws InterruptedException {
        E e;
        lock.lock();
        try {
            // 队列为空,在notEmpty条件上等待
            while (list.size() < 2) {
                notEmpty.await();
            }
            // 出队:移除链表首元素
            e = list.removeFirst();
            System.out.println("出队：" + e);
            // 通知在notFull条件上等待的线程
            notFull.signal();
            return e;
        } finally {
            lock.unlock();
        }
    }
}
